package io.gitee.zhangbinhub.admin.deploy.base

import com.mybatisflex.core.paginate.Page
import com.mybatisflex.core.query.QueryChain
import com.mybatisflex.core.table.TableInfoFactory
import io.gitee.zhangbinhub.acp.core.common.CommonTools
import io.gitee.zhangbinhub.admin.common.po.QueryParam
import io.gitee.zhangbinhub.admin.common.vo.CustomerQueryPageVo

/**
 * @since JDK 11
 */
abstract class BaseService {
    protected inline fun <reified T> doPageQuery(
        queryParam: QueryParam,
        queryChain: QueryChain<T>,
        withRelations: Boolean = false
    ): CustomerQueryPageVo<T> {
        if (!CommonTools.isNullStr(queryParam.orderName)) {
            val tableInfo = TableInfoFactory.ofEntityClass(T::class.java)
            queryParam.orderName!!.split(",").forEach { orderProperty ->
                queryChain.orderBy(
                    tableInfo.getQueryColumnByProperty(orderProperty),
                    queryParam.orderCommand.equals("asc", true)
                )
            }
        }
        return (if (withRelations) {
            queryChain.withRelations().page(Page(queryParam.currPage, queryParam.pageSize))
        } else {
            queryChain.page(Page(queryParam.currPage, queryParam.pageSize))
        }).let { pageResult ->
            CustomerQueryPageVo(
                content = pageResult.records,
                totalElements = pageResult.totalRow,
                currPage = queryParam.currPage!!,
                pageSize = queryParam.pageSize!!
            )
        }
    }
}
